//juqery的核心函数  文档加载完毕自动调用
var sx = null;
var sx02 = null;
var id = localStorage.getItem('studentId')
$(function () {
    getData();
})
//选中付费订单信息
var order = {}

//封装ajax 发送请求获取Tree数据
function getData() {
    //ajax 请求数据库，后台返回一个tree需要的数据，及对应的格式
    $.ajax({
        type: 'post',
        url: '/getStudentStandard',
        data: {'studentId': id},
        dataType: 'json',
        success: function (res) {
            getTree(res)
        },
        error: function (e) {
            console.log('请求失败')
        }
    })
}

//封装方法渲染Tree，方便自动更新页面
function getTree(data) {
    layui.use(['tree', 'layer', 'jquery', 'form', 'table'], function () {
        var tree = layui.tree;
        var layer = layui.layer;
        var $ = layui.$;
        var form = layui.form;
        var table = layui.table;


        //点击弹出选择班级
        $("#xz").click(function () {
            var index = null;
            index = layer.open({
                type: 2,
                title: '选择入学班级',
                content: 'classifyClassTree.html',
                area: ['80%', '80%']
            })
        })

        //监听添加订单分类和订单按钮
        form.on('submit(addFl)', function () {
            console.log('添加分类')
            layer.confirm('添加订单分类和订单', function (index) {
                layer.open({
                    type: 2,
                    title: '添加订单',
                    content: 'addFee.html',
                    area: ['100%', '100%']
                })
                layer.close(index)
            })
        })
        //监听添加订单按钮
        form.on('submit(addDD)', function () {
            layer.confirm('添加订单', function (index) {
                var classesId = $("[name=classesId]").val()
                console.log(classesId)
                if (classesId != '' && classesId != undefined) {
                    layer.open({
                        type: 2,
                        title: '添加订单',
                        content: 'addFee.html',
                        area: ['100%', '100%'],
                        success: function (layero, index) {
                            //父页面向子页面传参 -- 向iframe层传数据
                            //获取iframe页面
                            var body = layer.getChildFrame('body', index);
                            body.find('#classId').val(classesId);
                        }
                    })
                } else {
                    layer.msg('请选择一个订单分类')
                }
                layer.close(index)
            })
        })

        //监听打印按钮
        form.on('submit(dy)', function (d) {
            var doc = null;
            //设计需求订单信息
            var allprice = 0 //已收总额
            if (order.length > 0) {
                    var ret = []
                    var idlist = []
                    $.each(order, function (i) {
                        allprice += order[i].haveFees
                        idlist.push(order[i].id)
                        ret.push({
                            documentRecevied: order[i].amountReceivable,//单列原始总金额
                            documentAnnul: order[i].preferentialPrice,//单列减免价格
                            documentMoney: order[i].haveFees,//单列项目待缴费用
                            documentTime:order[i].generatedTime.slice(0,4),//订单创建时间
                            documnentCharge:order[i].projectName,
                        })
                    })
                    doc = {
                        idlist: idlist,
                        project: ret,
                        documentId: order[0].projectId,//订单id
                        actualPrice:allprice,//已收金额
                        payee: JSON.parse(sessionStorage.getItem("user")).userName//收款人
                    }
            }
            if (doc == null){
                layer.msg('至少选择一条订单信息进行打印',{icon:5,time:1500})
            }else {
                printSelect(d.field,doc)
            }
        })

        //监听提交保存按钮
        form.on('submit(*)', function (d) {
            if (d.field.haveFees == ""){
                layer.msg('请选择要交费的单据',{icon:5,time:1000})
                return false
            }else {
                if(table.getData('sx02').length != 1){
                    layer.msg('单次交费限制一条数据',{icon:5,time:1000})
                    return false;
                }
                //发送ajax修改选择的学生订单信息
                $.ajax({
                    type: 'post',
                    url: '/haveFee',
                    data: {
                        id:table.getData('sx02')[0].id,
                        haveFees:d.field.haveFees,
                        documentWay:d.field.documentWay
                    },
                    dataType: 'json',
                    success: function (res) {
                        if (res.state == '200') {
                            layer.msg('交费成功', {time: 1500, icon: 6}, function () {
                                setTimeout('window.location.reload()', 1000);
                            })
                        } else {
                            layer.msg('交费失败', {time: 1500, icon: 6}, function () {
                                var index = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(index);
                            })
                        }
                    },
                    error: function (e) {
                        console.log('请求失败')
                    }
                })
            }

        })

        //监听分期按钮
        form.on('submit(fq)', function (d) {
            console.log(d.field)
            layer.open({
                type: 2,
                title: '选择分期',
                content: 'Staging.html',
                area: ['60%', '60%'],
                //弹出层成功弹出后的回调函数
                success: function (layero, index) {
                    //父页面向子页面传参 -- 向iframe层传数据
                    //获取iframe页面
                    var body = layer.getChildFrame('body', index);

                }
            })
        })

        //实例化渲染树
        //定义一个全局集合，存储需要查询的列表
        var idList = []
        tree.render({
            elem: '#test1',
            id: 'demoId',
            data: data,
            showCheckbox: true,
            oncheck: function (obj) {
                //定义一个集合择取所有选项
                if (obj.checked == true) {
                    var data = obj.data
                    if (!obj.data.children) {
                        //子节点根据id查订单
                        console.log('子节点')
                        idList.push(obj.data.id)
                    } else {
                        // 有子节点
                        $.each(obj.data.children, function (i) {
                            idList.push(obj.data.children[i].id)
                        })
                    }
                } else {
                    if (!obj.data.children) {
                        var index = idList.findIndex(item => {
                            return item == obj.data.id
                        })
                        console.log("需要删除的元素下角标", index)
                        //取消选中删除对应的id
                        idList.splice(index, 1)
                    } else {
                        // 有子节点
                        $.each(obj.data.children, function (i) {
                            var index = idList.findIndex(item => {
                                return item == obj.data.children[i].id
                            })
                            idList.splice(index, 1)
                        })
                    }

                }
                if (idList.length == 0) {
                    sx02.reload({url: '/standard/getStantardArrearageByInfo',
                        where: {info: localStorage.getItem("studentId")},
                    },)
                } else {
                    sx02.reload({
                        url: '/standard/getStantardArrearageById',
                        where: {
                            idList: JSON.stringify(idList)
                        },
                        done(d) {
                            console.log("计算总汇",d)
                            total(d)
                            order = d.data
                        }
                    })
                }
            },
        })

        //付费算法
        function total(d) {
            var all = d.data
            console.log(all)
            var money = {preferentialPrice: 0, arrearage: 0, haveFees: 0}
            $.each(all, function (i) {
                money.preferentialPrice += all[i].preferentialPrice    //减免计算
                money.arrearage += all[i].arrearage //订单总额应收
                money.haveFees += all[i].haveFees //已收费用
            })
            console.log("money",money)
            //映射到页面
            $('input[name=preferentialPrice]').val(money.preferentialPrice)
            $('input[name=arrearage]').val(money.arrearage)
            $('input[name=haveFees]').val(money.haveFees)
        }


        //实例化渲染欠费表格
        sx = table.render({
            elem: '#demo',
            url: '/standard/getStantardArrearageByInfo',
            height: 200,
            where: {info: localStorage.getItem("studentId")},
            page: {
                layout: ['count', 'prev', 'page', 'next', 'limit'],
                groups: 5,
                limit: 10,
                limits: [3, 5, 10]
            },
            cols: [
                [
                    {field: 'projectId', title: '订单单号', width: 120, align: 'center'},
                    {field: 'projectName', title: '项目名称', width: 120, align: 'center'},
                    {field: 'arrearage', title: '剩余待缴', width: 110, align: 'center'},
                    {field: 'amountReceivable', title: '总金额', width: 120, align: 'center'},
                    {field: 'preferentialPrice', title: '减免金额', width: 100, align: 'center'},
                    {field: 'haveFees', title: '已收金额', width: 122, align: 'center'},
                    // {field: 'remark', title: '备注信息', width: 120, align: 'center'}
                ]
            ],
            parseData: function (res) {
                return {
                    "code": res.code,
                    "msg": res.msg,
                    "count": res.count,
                    "data": res.data
                }
            }
        })


        //实例化渲染表格
        sx02 = table.render({
            elem: '#demo02',
            url: '/standard/getStantardByInfo',
            where: {info: localStorage.getItem("studentId")},
            height: 260,
            id:'sx02',
            page: {
                layout: ['count', 'prev', 'page', 'next', 'limit'],
                groups: 5,
                limit: 10,
                limits: [3, 5, 10]
            },
            cols: [
                [
                    {
                        field: '', title: '序号', width: 80, templet(d) {
                            return d.LAY_INDEX
                        }, align: 'center'
                    },
                    {field: 'projectId', title: '订单单号', width: 140, align: 'center'},
                    {field: 'projectName', title: '项目名称', align: 'center'},
                    {field: 'arrearage', title: '剩余待缴', width: 100, align: 'center'},
                    {field: 'amountReceivable', title: '总金额', width: 100, align: 'center'},
                    {field: 'preferentialPrice', title: '减免金额', width: 100, align: 'center'},
                    {field: 'haveFees', title: '已收金额', width: 100, align: 'center'},
                    {field: 'remark', title: '备注信息', width: 120, align: 'center'}
                ]
            ],
            parseData: function (res) {
                return {
                    "code": res.code,
                    "msg": res.msg,
                    "count": res.count,
                    "data": res.data
                }
            },
            done(d) {
            }
        })
    })
}

//自定义打印页面
function printSelect(Student,Document) {

    //用于包含内容
    var v = document.createElement("div");
    //页面头部，导入css  ，media="print"表示打印时使用该样式
    var f = ["<head>", "<style>",
        "th{height: 30px;font-weight:500 ;}",
        "h1{font-weight:500 ;}",
        "</style>", "</head>"
    ].join("");
    var contentHtml = "";
    var template = ""
    var head =
        "<div style= 'width: 80%; margin: 0 auto;'>" +
        "<div style= 'overflow: hidden; box-sizing:border-box; '>" +
        "<h1 style= 'width: 200px; margin: 0 auto; padding-top: 20px;'>进思学生单据</h1>" +
        "<div style= 'margin-bottom: 5px; margin-top: 5px;width: 200px; margin-left: 100px; float: left' > " +
        "单据号：" + Document.documentId +
        "</div>"+
        "<div style= 'margin-bottom: 5px; margin-top: 5px;width: 200px; margin-right: 100px; float: right' > " +
        "市场部：" + Student.marketingName +
        "</div>"+
        "</div>"+
        "<table border='1' cellSpacing='0' style='width: 100%;'>" +
        "<tr>" +
        "<th>学号</th>" +
        "<th>"+ Student.studentId +"</th>" +
        "<th>姓名</th>" +
        "<th>"+ Student.studentName +"</th>" +
        "<th>班级</th>" +
        "<th>"+ Student.classesName +"</th>" +
        "</tr>" +
        "<tr>"+
        "<th>学期</th>"+
        "<th>"+ Student.studentSchoolTerm +"</th>"+
        "<th colSpan='2''>入学时间</th>"+
        "<th colSpan='2'>"+ Student.studentCreateDate +"</th>"+
        "</tr>"+
        "<tr>"+
        "<th colspan='2'>收费项目</th>"+
        "<th>收费标准</th>"+
        "<th>收费金额</th>"+
        "<th>单据减免</th>"+
        "<th>单据年份</th>"+
        "</tr>"
    var body = "";
        for (var i = 0 ; i < Document.project.length ; i++){
         body +=
            "<tr>"+
            "<th colspan='2'>"+ Document.project[i].documnentCharge +"</th>"+
            "<th>"+ Document.project[i].documentRecevied +".00</th>"+
            "<th>"+ Document.project[i].documentMoney +".00</th>"+
            "<th>"+ Document.project[i].documentAnnul +"</th>"+
            "<th>"+ Document.project[i].documentTime +"</th>"+
            "</tr>"
        }
    var food =
        "<tr>"+
        "<th colspan='2'></th>"+
        "<th></th>"+
        "<th></th>"+
        "<th></th>"+
        "<th></th>"+
        "</tr>"+
        "<tr>"+
        "<th colspan='2'></th>"+
        "<th></th>"+
        "<th></th>"+
        "<th></th>"+
        "<th></th>"+
        "</tr>"+
        "<tr>"+
        "<th style='border-right:hidden;'>行政事业性收费小计：</th>"+
        "<th colSpan='4' style='border-left:hidden; border-right: hidden; '></th>"+
        "<th style='border-left:hidden ;'>￥"+ Document.actualPrice +".00</th>"+
        "</tr>"+
        "<tr>"+
        "<th>合计金额（大写）</th>"+
        "<th style='border-right: hidden;'>"+ changeNumMoneyToChinese(Document.actualPrice) +"</th>"+
        "<th colSpan='3' style='border-left: hidden; border-right: hidden;'></th>"+
        "<th style='border-left: hidden;'>￥"+Document.actualPrice +".00</th>"+
        "</tr>"+
        "</table>"+

        "<div style='margin-left: 600px; width: 200px; padding-top:5px ;'>收款人："+ Document.payee +"</div>"+
        "</div>"

    template += head;
    template += body;
    template += food;
    contentHtml += template;
    //contentHtml为已拼凑好的内容
    $(v).append(contentHtml)

    //新建窗口
    var h = window.open("打印窗口", "_blank");
    //写入拼凑内容
    h.document.write(f + $(v).prop("outerHTML"));

    //调用打印
    h.print(
        //发送ajax 添加到打印信息表里
        $.ajax({
            type:'post',
            url:'/addPrint',
            data:{
                studentId : Student.studentId,
                documentId : Document.documentId,
                idlist: JSON.stringify(Document.idlist)
            },
            dataType: 'json',
            success:function (res){
                if (res.state == '200'){
                   layer.msg('打印请求成功')
                }

            },
            error:function (e){
                layer.msg('打印请求失败')
                console.log(e)
            }

        })
    );
    //关闭页面
    h.close();

}

//数子转换大写格式
function changeNumMoneyToChinese(money) {
    var cnNums = new Array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"); //汉字的数字
    var cnIntRadice = new Array("", "拾", "佰", "仟"); //基本单位
    var cnIntUnits = new Array("", "万", "亿", "兆"); //对应整数部分扩展单位
    var cnDecUnits = new Array("角", "分", "毫", "厘"); //对应小数部分单位
    var cnInteger = "整"; //整数金额时后面跟的字符
    var cnIntLast = "元"; //整型完以后的单位
    var maxNum = 999999999999999.9999; //最大处理的数字
    var IntegerNum; //金额整数部分
    var DecimalNum; //金额小数部分
    var ChineseStr = ""; //输出的中文金额字符串
    var parts; //分离金额后用的数组，预定义
    var Symbol = ""; //正负值标记
    if (money == "") {
        return "";
    }

    money = parseFloat(money);
    if (money >= maxNum) {
        alert('超出最大处理数字');
        return "";
    }
    if (money == 0) {
        ChineseStr = cnNums[0] + cnIntLast + cnInteger;
        return ChineseStr;
    }
    if (money < 0) {
        money = -money;
        Symbol = "负 ";
    }
    money = money.toString(); //转换为字符串
    if (money.indexOf(".") == -1) {
        IntegerNum = money;
        DecimalNum = '';
    } else {
        parts = money.split(".");
        IntegerNum = parts[0];
        DecimalNum = parts[1].substr(0, 4);
    }
    if (parseInt(IntegerNum, 10) > 0) { //获取整型部分转换
        var zeroCount = 0;
        var IntLen = IntegerNum.length;
        for (var i = 0; i < IntLen; i++) {
            var n = IntegerNum.substr(i, 1);
            var p = IntLen - i - 1;
            var q = p / 4;
            var m = p % 4;
            if (n == "0") {
                zeroCount++;
            } else {
                if (zeroCount > 0) {
                    ChineseStr += cnNums[0];
                }
                zeroCount = 0; //归零
                ChineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
            }
            if (m == 0 && zeroCount < 4) {
                ChineseStr += cnIntUnits[q];
            }
        }
        ChineseStr += cnIntLast;
        //整型部分处理完毕
    }
    if (DecimalNum != '') { //小数部分
        var decLen = DecimalNum.length;
        for (var i = 0; i < decLen; i++) {
            var n = DecimalNum.substr(i, 1);
            if (n != '0') {
                ChineseStr += cnNums[Number(n)] + cnDecUnits[i];
            }
        }
    }
    if (ChineseStr == '') {
        ChineseStr += cnNums[0] + cnIntLast + cnInteger;
    } else if (DecimalNum == '') {
        ChineseStr += cnInteger;
    }
    ChineseStr = Symbol + ChineseStr;

    return ChineseStr;
}


